<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- gutter是栅栏间隔的意思 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入商品名" v-model="getGoods.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="showAddGoodsPage">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="goodsList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="goods_name"
          label="商品名称"
          width="500%"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column prop="goods_price" label="商品价格" width="100%" align="center"></el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="100%" align="center"></el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="200%" align="center">
          <!-- 时间过滤器 -->
          <template slot-scope="scope">{{scope.row.add_time|timeFormat}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="info"
              icon="el-icon-edit"
              size="mini"
              @click="showEditGoodsDialog(scope.row.goods_id)"
            >设置</el-button>
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="mini"
              @click="delGoods(scope.row.goods_id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getGoods.pagenum"
        :page-sizes="[2,4,6,8,10]"
        :page-size="getGoods.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalGoods"
      ></el-pagination>
    </el-card>
    <!-- 修改对话框 -->
    <el-dialog
      title="修改商品"
      :visible.sync="editGoodsdialogVisible"
      width="40%"
      @close="delEditGoodsForm"
    >
      <el-form :model="editGoodsForm" ref="editGoodsRef">
        <el-form-item label="商品名" label-position="left" label-width="80px">
          <el-input v-model="editGoodsForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" label-position="left" label-width="80px">
          <el-input v-model="editGoodsForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" label-position="left" label-width="80px">
          <el-input v-model="editGoodsForm.goods_weight"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" label-position="left" label-width="80px">
          <el-input v-model="editGoodsForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" label-position="left" label-width="80px">
          <el-cascader
            v-model="editGoodsForm.goods_cat"
            :options="categoriesList"
            :props="cateListProp"
            @change="selectCateChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" editclass="dialog-footer">
        <el-button @click="editGoodsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      goodsList: [],
      // 设置获取列表参数
      getGoods: {
        query: '',
        pagenum: 1,
        pagesize: 6
      },
      totalGoods: 0,
      editGoodsForm: {},
      editGoodsdialogVisible: false,
      categoriesList: [],
      cateListProp: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      }
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      const { data: ret } = await this.$http.get('goods', {
        params: this.getGoods
      })
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.goodsList = ret.data.goods
      this.totalGoods = ret.data.total
    },
    handleSizeChange(e) {
      this.getGoods.pagesize = e
      this.getGoodsList()
    },
    handleCurrentChange(e) {
      this.getGoods.pagenum = e
      this.getGoodsList()
    },
    showAddGoodsPage() {
      this.$router.push('/goods/addgoods')
    },
    async showEditGoodsDialog(id) {
      // 显示修改对话框
      // 发请求获取分类列表
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoriesList = res.data
      // 发请求获取商品信息
      this.editGoodsdialogVisible = true
      const { data: ret } = await this.$http.get('goods/' + id)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      ret.data.goods_cat = ret.data.goods_cat
        .split(',')
        .map(item => Number(item))
      this.editGoodsForm = ret.data
      // this.editGoodsForm.goods_cat = [19, 6, 23]
      console.log(this.editGoodsForm)
    },
    selectCateChange() {
      console.log(this.editGoodsForm.goods_cat)
    },
    delGoods(id) {
      // 删除商品
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete('goods/' + id)
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message.success(ret.meta.msg)
          this.getGoodsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    delEditGoodsForm() {
      // 关闭对话框清除表单
      this.$refs.editGoodsRef.resetFields()
    },
    async doEditGoods() {
      // 完成修改商品
      // 将goods_cat转换成字符串
      const cloneForm = _.cloneDeep(this.editGoodsForm)
      cloneForm.goods_cat = cloneForm.goods_cat.join(',')
      const { data: ret } = await this.$http.put(
        'goods/' + this.editGoodsForm.goods_id,
        cloneForm
      )
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
      this.editGoodsdialogVisible = false
      this.getGoodsList()
    }
  }
  // filters: {
  //   // 可以将过滤器在main.js设置为全局，订单列表那里也用
  //   timeFormat(val) {
  //     const date = new Date(val)
  //     const Y = date.getFullYear()
  //     const M = (date.getMonth() + 1 + '').padStart(2, '0')
  //     const D = (date.getDate() + '').padStart(2, '0')
  //     const h = (date.getHours() + '').padStart(2, '0')
  //     const m = (date.getMinutes() + '').padStart(2, '0')
  //     const s = (date.getSeconds() + '').padStart(2, '0')
  //     return `${Y}-${M}-${D} ${h}:${m}:${s}`
  //   }
  // }
}
</script>

<style lang='less' scoped>
.el-cascader {
  width: 100%;
}
</style>
